package com.decent.ejfadmin.common.util;

import com.decent.ejfadmin.common.bean.NotifyWeChatBean;
import com.decent.ejfadmin.config.PlatUrlConfig;
import com.decent.ejfadmin.utils.Httpclient;
import com.decent.ejfadmin.utils.Md5;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadFactory;

import static java.util.concurrent.Executors.newFixedThreadPool;

/**
 * describe:钉钉推送工具
 *
 * @author JunLei He
 * @date 2018年10月12日
 */
@Slf4j
@Component
public class DingTalkMessagePush {
    private static final ThreadFactory THREAD_FACTORY = new ThreadFactoryBuilder().setNameFormat("DingTalkMessagePush-%d")
            .setDaemon(true).build();
    private static final ExecutorService MESSAGE_PUSHING_POOL = newFixedThreadPool(10, THREAD_FACTORY);
    private static final String MESSSAGE_KEY = "sendWxMsgdlk";
    private static final String RESULT_OK = "0";
    @Autowired
    private PlatUrlConfig platUrlConfig;


    /**
     * 微信提现消息推送用户
     *
     * @param notify 微信消息通知实体
     * @return 返回消息
     */
    public void withdrawMessagePushingToWeiChat(NotifyWeChatBean notify) {
        MESSAGE_PUSHING_POOL.execute(() -> {
            try {
                StringBuffer url = new StringBuffer(100);
                url.append(platUrlConfig.getWeiXinMessage()).append("Handler/SendWxMsg/SendMoneyMsg.ashx");
                NameValuePair[] nvps = new NameValuePair[10];
                String time = String.valueOf(System.currentTimeMillis());
                StringBuffer sign = new StringBuffer();
                sign.append("key=").append(MESSSAGE_KEY)
                        .append("&loginAccount=").append(notify.getLoginAccount())
                        .append("&money=").append(notify.getMoney().setScale(2, BigDecimal.ROUND_HALF_UP))
                        .append("&openid=").append(notify.getOpenid())
                        .append("&orderId=").append(notify.getOrderId())
                        .append("&realName=").append(notify.getRealName())
                        .append("&startTime=").append(DateUtils.parseDate(notify.getStartTime(), "yyyy-MM-dd HH:mm:ss").getTime())
                        .append("&status=").append(notify.getStatus())
                        .append("&timestamp=").append(time)
                        .append("&withdrawAccount=").append(notify.getWithdrawAccount());
                nvps[0] = new BasicNameValuePair("openid", notify.getOpenid());
                nvps[1] = new BasicNameValuePair("loginAccount", notify.getLoginAccount());
                nvps[2] = new BasicNameValuePair("withdrawAccount", URLEncoder.encode(notify.getWithdrawAccount(), "UTF-8"));
                nvps[3] = new BasicNameValuePair("money", String.valueOf(notify.getMoney().setScale(2, BigDecimal.ROUND_HALF_UP)));
                nvps[4] = new BasicNameValuePair("orderId", notify.getOrderId());
                nvps[5] = new BasicNameValuePair("startTime", String.valueOf(DateUtils.parseDate(notify.getStartTime(), "yyyy-MM-dd HH:mm:ss").getTime()));
                nvps[6] = new BasicNameValuePair("status", String.valueOf(notify.getStatus()));
                nvps[7] = new BasicNameValuePair("timestamp", time);
                nvps[8] = new BasicNameValuePair("signStr", Md5.getMd5(sign.toString(), true, "UTF-8").toLowerCase());
                nvps[9] = new BasicNameValuePair("realName", URLEncoder.encode(notify.getRealName(), "UTF-8"));
                log.info("微信通知用户接口url:[{}],参数:[{}]", url, nvps);
                int pushCount = 0;
                String result;
                do {
                    result = Httpclient.post(url.toString(), Arrays.asList(nvps), "UTF-8", 30000, 30000);
                    pushCount++;
                    log.info("微信通知用户接口[{}]-返回值[{}]", url.toString(), result);
                    if (StringUtils.isNotBlank(result) && RESULT_OK.equals(result)) {
                        break;
                    }
                } while (pushCount < 3);
            } catch (Exception e) {
                log.warn("[{}]微信通知用户失败,异常[{}]", notify, e);
            }
        });

    }
    /**
     * 钉钉机器人推送
     *
     * @param content 消息内容
     * @param webHook 机器人地址
     */
    public void dingDingRobotPushing(String content, String webHook) {
        //利用线程池去创建执行任务
        MESSAGE_PUSHING_POOL.execute(() -> {
            try {

                HttpClient httpclient = HttpClients.createDefault();
                HttpPost httppost = new HttpPost(webHook);
                httppost.addHeader("Content-Type", "application/json; charset=utf-8");
                String textMsg = "{ \"msgtype\": \"text\", \"text\": {\"content\":\"" + content + "\"}}";
                StringEntity se = new StringEntity(textMsg, "utf-8");
                httppost.setEntity(se);
                HttpResponse response = httpclient.execute(httppost);
                String result = null;
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    result = EntityUtils.toString(response.getEntity(), "utf-8");
                }
                log.info("钉钉机器人推送内容:[{}],返回[{}]", content, result);
            } catch (Exception e) {
                log.warn("钉钉机器人推送内容:[{}],异常[{}]", content, e);
            }
        });
    }
}
